<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AdminImpersonationLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'admin_user_id',
        'target_tenant_id',
        'target_user_id',
        'start_time',
        'end_time',
        'ip_address',
        'reason',
        'status'
    ];

    protected $casts = [
        'start_time' => 'datetime',
        'end_time' => 'datetime'
    ];

    // 关联A端用户
    public function adminUser()
    {
        return $this->belongsTo(AdminUser::class);
    }

    // 关联目标租户
    public function targetTenant()
    {
        return $this->belongsTo(Tenant::class, 'target_tenant_id');
    }

    // 关联目标用户
    public function targetUser()
    {
        return $this->belongsTo(User::class, 'target_user_id');
    }

    // 身份切换状态常量
    const STATUS_ACTIVE = 'active';         // 进行中
    const STATUS_ENDED = 'ended';           // 已结束
    const STATUS_EXPIRED = 'expired';       // 已过期

    // 获取状态显示名称
    public function getStatusDisplayAttribute()
    {
        $statuses = [
            self::STATUS_ACTIVE => '进行中',
            self::STATUS_ENDED => '已结束',
            self::STATUS_EXPIRED => '已过期'
        ];

        return $statuses[$this->status] ?? $this->status;
    }

    // 获取持续时间
    public function getDurationAttribute()
    {
        if (!$this->end_time) {
            return $this->start_time->diffForHumans(now());
        }

        return $this->start_time->diffForHumans($this->end_time);
    }

    // 结束身份切换
    public function endImpersonation()
    {
        $this->end_time = now();
        $this->status = self::STATUS_ENDED;
        return $this->save();
    }

    // 记录身份切换开始
    public static function startImpersonation($adminUserId, $targetTenantId, $targetUserId = null, $reason = null)
    {
        return self::create([
            'admin_user_id' => $adminUserId,
            'target_tenant_id' => $targetTenantId,
            'target_user_id' => $targetUserId,
            'start_time' => now(),
            'ip_address' => request()->ip(),
            'reason' => $reason,
            'status' => self::STATUS_ACTIVE
        ]);
    }
}